import baseUrl  from './config.js';

function request(obj) {
	return new Promise((resolve, reject) => {
		let method = obj.method || 'GET';
		let url = '';
		let data = obj.data || {};
		let token = uni.getStorageSync('userToken');
		// let token = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjI5YjhmZTlkLTA4ZjQtNGM1MC1hMTA4LWE0M2U0MmMzOTczYyJ9.Z6-b9C9qeh8kiw947tyVWLLFZ646ME9OxboQMXGaDK0SWeR3K7XK1M7-IjjzTYrrTmF2iiv9WT2AnIvowc7dyA';
		let header = '';
		let facility = uni.getSystemInfoSync().platform; //设备
		let success = obj.success; //成功返回
		let fail = obj.fail; //错误回调
		
		let bss = uni.getStorageSync('webUrl') == ''? baseUrl.baseUrl: uni.getStorageSync('webUrl');

		// 根据设备调整ajax请求
		if(obj.url.indexOf('http://')>=0){
			url = bss + obj.url
		}else if (facility === 'android') {
			url = bss + obj.url
		} else {
			console.log('======是H5======');
			url = bss + obj.url
		}
		//判断登录还是其他请求添加token信息
		if (obj.url === '/loginExt') {
			header = {
				'Content-Type': 'application/json'
			}
		}else if(obj.url.indexOf('http://')>=0){
			header = {}
		} else {
			header = {
				'Content-Type': 'application/json',
				'Authorization': 'Bearer ' + token,
			}
		}

		/*请求方法*/
		uni.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success: ((res) => {
				let code = res.statusCode;
				let entity = res.data;
				uni.hideLoading();
				if (entity.code === 10403 || entity.code === 10401) {
					uni.showModal({
					    title: '提示',
					    content: '请先去登录.',
					    success: res => {
					        if (res.confirm) {
								uni.removeStorageSync('inForm');
								uni.removeStorageSync('inIndex');
								uni.removeStorageSync('inMergeList');
								uni.removeStorageSync('isFlush');
								uni.removeStorageSync('isNumber');
								uni.removeStorageSync('moveForm');
								uni.removeStorageSync('outForm');
								uni.removeStorageSync('outIndex');
								uni.removeStorageSync('outMergeList');
								uni.removeStorageSync('stockInfo');
								uni.removeStorageSync('userId');
					            uni.reLaunch({
					            	url: '/pages/index/index'
					            })
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					        }
					    }
					});
					return;
				} else if (code === 200) {
					resolve(entity)
				} else {
					if(obj.url.indexOf('http://')<0){
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						})
					}
					reject(entity)
				}
			})
			// fail((error) => {
			// 	console.log(error, 'error//////error')
			// })
		})
	})
}

export default request
